//删除的id

var delId = [];
var delId2 = [];

//	时间初试化
$('#beginDateAdd').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#beginDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endDateAdd').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});

var oprateUrl = DOMAIN + '/v1/priceTab' + isLogin;
function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 50,
		pageNumber: 1,
		pageList: [50, 100],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [/*{
			checkbox: true
		}, */{
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "code",
			title: "价格表代码",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "name",
			title: "价格表名称",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "beginDate",
			title: "起始日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "endDate",
			title: "截止日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "comments",
			title: "备注",
			align: "center",
			valign: "middle",
			sortable: "true"
		},{
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function (value, row, index) {
				if (row.deleteFlg == 1) {
					return '<button priceNo="' + row.code + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">编辑</button>';
				} else {
					return '<button priceNo="' + row.code + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;编辑</button> <button data-del="' + oprateUrl + '" class="btn btn-primary btn-sm del">&emsp;删除</button>';
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt',],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0],  //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function () {
			return '没有找到匹配的记录';
		}
	});
	function queryParams(params) {
		var params = {};
		return params;
	};
}

//查询
$("#selectPurchaseBtn").click(function () {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.beginDate = $("#beginDate").val();
		params.endDate = $("#endDate").val();
		params.name = $("#priceTabName").val();
		return params;
	};
	var url = DOMAIN + '/v1/priceTab' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

//批量新增


$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	pageNumber: 1,
	pageList: [200, 500],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productName",
		title: "产品名称",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "productCode",
		title: "产品代码",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productType",
		title: "产品类别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}/*, {
		field: "specifications",
		title: "规格",
		align: "center",
		valign: "middle",
		sortable: "true"
	}*/, {
		field: "grade",
		title: "产品级别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "units",
		title: "单位",
		align: "center",
		valign: "middle",
		sortable: "true"
	},{
		field: "price",
		title: "单价",
		align: "center",
		valign: "middle",
		formatter: function (value, row, index) {
			if(isEmpty(row.price)){
				row.price = 0;
			}
			return row.price;
		},
		cellStyle:function(value,row,index){
			return {css:{"color":"#0088cc"}} 
		}
	}],
	formatNoMatches: function () {
		return '';
	},
	onClickCell: function(field, value, row, $element) {
		if(field=="price"){
    		$element.attr('contenteditable', true);
       		$element.blur(function() {
       			if($element.html()=="" || isNaN($element.html())){
       					$element.html(value);
       			}else{
       				let index = $element.parent().data('index');
            		let tdValue = $element.html();
            		saveData(index, field, tdValue);
       			}
       		});
    	}
	}
	//保存的使用
});

 function saveData(index, field, value) {
        $("#tableAddDetail").bootstrapTable('updateCell', {
            index: index,       
            field: field,       //列名
            value: value        //cell值
        });
}
 
function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function () {

	//获取数据
	var productCode = $('#productCode').val();
	var productName = $('#productName').val();
	//判断商品是否已在明细中
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].productCode == productCode) {
			alert("商品" + productName + "已经存在，请输入其他商品");
			return;
		}
	}
	var productType = $('#productType').val();
	var specifications = $('#specifications').val();
	var grade = $('#grade').val();
	var units = $('#units').val();
	var price = $('#price').val();
	
	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	//var t = $('#info').serializeArray();
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			productName: productName,
			productCode: productCode,
			productType: productType,
			specifications: specifications,
			grade: grade,
			units: units,
			price: price
		}
	});
	//新增后置空
	$('#info')[0].reset();
});


	
	
	
	
//保存
$("#AddPur-saveBtn").click(function () {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);;
	if (!flag) {
		//alert("请先输入数据");
		return;
	}
	params = JSON.stringify(params);
	//进货id是否绑定,没有id就新增
	var mainId = $('#mainId').val();
	if (mainId == '' || mainId == null) {
		$.ajax({
			type: "post",
			url: DOMAIN + '/v1/priceTab' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('保存失败');
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#customer_form')[0].reset();
		$('#mainId').val('');
		$('.close').click();
	} else {
		//更新
		$.ajax({
			type: "patch",
			url: DOMAIN + '/v1/priceTab/' + mainId + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {

					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
				if (result.status == 402) {
					alert(result.msg);
				}
			},
			error: function () {
				alert('编辑失败');
			},
			complete: function () {
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#customer_form')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId = [];
	}
});

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};
	params.beginDate = $("#beginDateAdd").val();
	params.endDate = $("#endDateAdd").val();
	params.name = $("#priceTabNameAdd").val();
	params.code = $("#code").val();
	params.comments = $("#comments").val();
	params.priceInfoList = rows;
	params.delId = delId;
	console.log(params);
	return params;

}

//删除选中行
$("#AddPur-deleteBtn").click(function () {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}

		}
	}
});


function isMainNull(t) {

	if (t.name == '' || t.name == null) {
		alert("价格表名称不能为空");
		return false;
	}
	if (t.beginDate == '' || t.beginDate == null) {
		alert("起始日期不能为空");
		return false;
	}
	if (t.endDate == '' || t.endDate == null) {
		alert("截止日期不能为空");
		return false;
	}
	return true;
}
function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	/*if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}*/
	return true;
}

//编辑信息
function EditInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#tableCustomerDetail').bootstrapTable('removeAll');
	$('#info')[0].reset();
	$('#customer_form')[0].reset();
	$("#change_Btn").css("display","block");
	//将删除的id置空
	delId = [];
	delId2 = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var priceNo = $(e).attr('priceNo');
	var url = DOMAIN + '/v1/priceInfo' + isLogin + '&priceNo=' + priceNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	
	var url2 = DOMAIN + '/v1/priceCustomer' + isLogin + '&priceNo=' + priceNo;
	$('#tableCustomerDetail').bootstrapTable(
		'refresh',
		{
			url: url2,
			//查询参数
			queryParams: queryParamNew
		}
	);
}

//新增前填写日期并获取批次号与进货编号
function resetTable() {
	//将删除的id置空
	delId = [];
	delId2 = [];
	$('#mainId').val(""); 
	$('#main1')[0].reset();
	$('#info')[0].reset();
	$('#customer_form')[0].reset();
	
	$("#change_Btn").css("display","none");

	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#tableCustomerDetail').bootstrapTable('removeAll');
	
	time_rota($("#beginDateAdd"));
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function (n, i) {
		indexed_array[n['name']] = n['value'];
	});
	return indexed_array;
};

//下拉框填充
$(function () {
	
	loadTable();
	$("#tableDetail_btn").css("background-image","url()");
	$("#Customer_info").css("display","none");
	$("#info").css("display","block");
	time_rota2($("#beginDate"));
	//time_rota($("#endDate"));
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.beginDate = $("#beginDate").val();
		params.endDate = $("#endDate").val();
		return params;
	};
	var url = DOMAIN + '/v1/priceTab' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
});

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function () {
	$("#customerDetail_btn").css("background-image","url(../img/btn-icon/btn-blue.jpg)");
	$("#tableDetail_btn").css("background-image","url()");
	$("#Customer_info").css("display","none");
	$("#Product_info").css("display","block");
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//关闭
$("#AddPur-closeBtn").click(function () {
	$("#close-btn")[0].click();
});

function selectCustomer(row){
	$("#customerName").val(row.name);
	$("#customerNo").val(row.code);
	$("#customerAddress").val(row.address);
	
}

function selectProduct(row){
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#specifications").val(row.specifications);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
}


$("#tableCustomerDetail").bootstrapTable({ // 对应table标签的id
	//url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 5,
	pageNumber: 1,
	pageList: [5, 10],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "customerNo",
		title: "客户代码",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "customerName",
		title: "客户名称",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "customerAddress",
		title: "客户地址",
		align: "center",
		valign: "middle",
		sortable: "true"
	}],
	formatNoMatches: function () {
		return '';
	}
	//保存的使用
});
function queryParams(params) {
	return params;
};

//新增客户按钮，不存到数据库
$("#Customer-insertBtn").click(function () {

	//获取数据
	var customerNo = $('#customerNo').val();
	var customerName = $('#customerName').val();
	//判断客户是否已在明细中
	var rows = $('#tableCustomerDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].customerName == customerName) {
			alert("客户" + customerName + "已经存在，请输入其他商品");
			return;
		}
	}
	var customerAddress = $('#customerAddress').val();
	
	var count = $('#tableCustomerDetail').bootstrapTable('getData').length;
	var options = $("#tableCustomerDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	if (isEmpty(customerNo)) {
		alert("请先选择客户");
		return;
	}
	$('#tableCustomerDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			customerNo: customerNo,
			customerName: customerName,
			customerAddress: customerAddress
		}
	});
	//新增后置空
	$('#customer_form')[0].reset();
});

//删除选中的客户
$("#Customer-deleteBtn").click(function () {
	var ids = $("#tableCustomerDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableCustomerDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableCustomerDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId2.push(id);
				}

		}

	}
});

//客户关闭按钮
$("#Customer-closeBtn").click(function () {
	$("#close-btn")[0].click();
});

$("#tableDetail_btn").click(function(){
	$("#customerDetail_btn").css("background-image","url(../img/btn-icon/btn-blue.jpg)");
	$("#tableDetail_btn").css("background-image","url()");
	$("#Customer_info").css("display","none");
	$("#Product_info").css("display","block");
});

$("#customerDetail_btn").click(function(){
	$("#tableDetail_btn").css("background-image","url(../img/btn-icon/btn-blue.jpg)");
	$("#customerDetail_btn").css("background-image","url()");
	$("#Product_info").css("display","none");
	$("#Customer_info").css("display","block");
});

//保存客户
$("#Customer-saveBtn").click(function () {
	//得到新增表格数据
	var params = getDataForAdd2();
	var flag = false;
	var flag = isMainNull(params);;
	if (!flag) {
		return;
	}
	params = JSON.stringify(params);
	//进货id是否绑定,没有id就新增
	var mainId = $('#mainId').val();
	if (mainId == '' || mainId == null) {
		$.ajax({
			type: "post",
			url: DOMAIN + '/v1/priceCustomer' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('保存失败');
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#customer_form')[0].reset();
		$('#mainId').val('');
		$('.close').click();
	} else {
		//更新
		$.ajax({
			type: "patch",
			url: DOMAIN + '/v1/priceCustomer/' + mainId + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {

					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
				if (result.status == 402) {

					alert(result.msg);
				}
			},
			error: function () {
				alert('编辑失败');
			},
			complete: function () {
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#customer_form')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId2 = [];
	}
});

//新增时获取数据的方法
function getDataForAdd2() {
	var rows = $('#tableCustomerDetail').bootstrapTable('getData');
	var params = {};
	params.beginDate = $("#beginDateAdd").val();
	params.endDate = $("#endDateAdd").val();
	params.name = $("#priceTabNameAdd").val();
	params.code = $("#code").val();
	params.comments = $("#comments").val();
	params.priceCustomerList = rows;
	params.delId2 = delId2;
	return params;

}